package com.cskaoyan.service;

import com.cskaoyan.bean.PO.MarketAddress;
import com.cskaoyan.bean.PO.MarketAddressExample;
import com.cskaoyan.bean.PO.MarketUser;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketAddressMapper;
import com.cskaoyan.mapper.WXAddressMapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author:zhangjiaxin
 **/
@Service
public class WxAddressServiceImpl implements WxAddressService {

    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    WXAddressMapper wxAddressMapper;

    //地址列表
    @Override
    public CommonData<MarketAddress> queryAddressList(MarketUser currentUser) {
        MarketAddressExample marketAddressExample = new MarketAddressExample();
        MarketAddressExample.Criteria criteria = marketAddressExample.createCriteria();
        //默认显示的为deleted为false的信息
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(currentUser.getId());
        List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);
        PageInfo<MarketAddress> pageInfo = new PageInfo<>(marketAddresses);
        return CommonData.data(pageInfo);
    }

    //查询地址具体信息
    @Override
    public MarketAddress queryByAddressDetail(Integer id) {
        MarketAddress address = marketAddressMapper.selectByPrimaryKey(id);
        return address;

    }

    //删除地址
    @Override
    public Integer deleteById(MarketAddress address) {
        //逻辑删除
        address.setDeleted(true);
        int affectRows = marketAddressMapper.updateByPrimaryKeySelective(address);
        if (affectRows == 0) {
            return null;
        }
        return affectRows;
    }

    //保存地址：新增+修改
    @Override
    public Integer save(MarketAddress marketAddress, Integer userId) {
        //如果地址设为默认地址，需要先找到之前的默认地址取消之后再更新
        if (marketAddress.getIsDefault() == true) {
            wxAddressMapper.updateIsDefault();
        }
        marketAddress.setUserId(userId);
        marketAddress.setDeleted(false);
        marketAddress.setAddTime(new Date());
        marketAddress.setUpdateTime(new Date());
        Integer id = marketAddress.getId();
        if (id != null && id != 0) {
            marketAddressMapper.updateByPrimaryKey(marketAddress);
            return id;
        }
        marketAddressMapper.insertSelective(marketAddress);
        return marketAddress.getId();
    }


}
